#include "gamecontrol.h"
#include "gamedefine.h"
#include"gameobjectpool.h"
#include"myplayer.h"
#include<QTextStream>
#include<QObject>
#include<QDebug>



GameControl* GameControl::instance= nullptr;
GameControl::GameControl()
{

}

void GameControl::GameInit()
{
    //对象池初始化
    GameObjectPool::Instance()->Init();

    //设置视图的父亲为窗口
    mGameView.setParent(Widget::widget);

    LoadStartScene();//开始场景初始化

    //定时器初始化
    mplayerMoveTimer = new QTimer(this);
    mEnemyfallingCreateTimer = new QTimer(this);
    mEnemyfallingMoveTimer =new QTimer(this);


    //绑定定时器处理函数
    connect(mplayerMoveTimer,&QTimer::timeout,this,&GameControl::playermove);
    connect(mEnemyfallingCreateTimer,&QTimer::timeout,this,&GameControl::Createfalling);
    connect(mEnemyfallingMoveTimer,&QTimer::timeout,[this](){
        //掉落物移动
        for(auto enemyfalling : mEnemyfallingList)
        {
            enemyfalling->EnemyfallingMove();

            //判断越界
            if(enemyfalling->y()>1024)
            {
                //移除场景，对象池回收对象
                enemyfalling->GameObjectDelete(&mGameScene);

                //移除容器
                mEnemyfallingList.removeOne(enemyfalling);


            }
        }

        //碰撞检测
        Collision();
    });

}

void GameControl::Collision()//z
{
    qDebug() << "Collision() function called.";
    QMutableListIterator<Enemyfalling *> it(mEnemyfallingList);
    while (it.hasNext())
    {
        Enemyfalling *currentFallingObject = it.next();
        if (currentFallingObject->collidesWithItem(&mmyplayer))
        {
            qDebug() << "Player collided with an item!";
            QString itemPixmapCacheKey = QString::number(currentFallingObject->pixmap().cacheKey());
            qDebug() << "Item CacheKey (as string):" << itemPixmapCacheKey;
            qDebug() << "Item actual pixmap resource path:" << currentFallingObject->data(Qt::UserRole + 1).toString();

            if (itemPixmapCacheKey.contains("bomb.png") || currentFallingObject->data(Qt::UserRole + 1).toString().contains("bomb.png"))
            {
                qDebug() << "It's a BOMB! Calling GameOver().";
                GameOver();
                return;
            }
            else
            {
                qDebug() << "It's not a bomb. Removing item.";
                currentFallingObject->GameObjectDelete(&mGameScene);
                it.remove();
            }
        }
    }
    // //遍历碰撞物
    // for(int j=0;j<mEnemyfallingList.size();j++)
    // {
    //     if(mEnemyfallingList[j]->collidesWithItem(&mmyplayer))
    //     {
    //         //z
    //         // QString imagePath;

    //         // // 根据掉落物类型处理不同逻辑
    //         // imagePath=(mEnemyfallingList[j]->pixmap().cacheKey()); // 获取掉落物图片路径

    //         // if(mEnemyfallingList[j])
    //         // {
    //         //     // 炸弹 - 游戏结束
    //          GameOver();
    //         //     return; // 直接结束游戏
    //         // }

    //         // else
    //         // {
    //         //     //移除场景，对象池回收对象
    //         //     mEnemyfallingList[j]->GameObjectDelete(&mGameScene);

    //         //     //移除容器
    //         //     mEnemyfallingList.removeOne(mEnemyfallingList[j]);


    //         // }
    //     }
    // }
}


void GameControl::LoadStartScene()
{
    mStartScene.setSceneRect(QRect(0,0,1024,1024));//游戏开始场景
    //开始场景初始化
    mStartScene.addPixmap(QPixmap(":/start/images/startscene.png"));

    auto startBtn=new QToolButton();
    startBtn->setAutoRaise(true);
    startBtn->resize(400,100);
    startBtn->setIcon(QIcon(":/start/images/startbutton.png"));
    startBtn->setIconSize(QSize(400,100));
    startBtn->move(312,700);
    //开始游戏点击
    connect(startBtn,&QToolButton::clicked,[this](){


        //加载游戏场景
        this->LoadGameScene();
        //开始游戏
        this->GameStart();

    });

    mStartScene.addWidget(startBtn);

    //设置当前场景为开始场景
    mGameView.setScene(&mStartScene);
    mGameView.show();
}

void GameControl::LoadGameScene()
{
    mGameScene.setSceneRect(QRect(0,0,1024,1024));//游戏进行场景
    mbackground.setPixmap(QPixmap(":/background/images/background.png"));
    mmyplayer.setPixmap(QPixmap(":/player/images/player.png"));

    //图片元素添加到场景
    mGameScene.addItem(&mbackground);
    mGameScene.addItem(&mmyplayer);







    //设置当前场景为游戏场景
    mGameView.setScene(&mGameScene);
    mGameView.show();
}

void GameControl::GameStart()
{
    //开启定时器
    mplayerMoveTimer->start(GameDefine::playerMoveTime);
    mEnemyfallingCreateTimer->start(GameDefine::EnemyfallingCreateTime);
    mEnemyfallingMoveTimer->start(GameDefine::EnemyfallingMoveTime);
}

void GameControl::GameOver()
{
    //结束逻辑
    // 1. 停止所有定时器
    mplayerMoveTimer->stop();
    mEnemyfallingCreateTimer->stop();
    mEnemyfallingMoveTimer->stop();

     // 2. 清空掉落物
    for (auto enemyfalling :mEnemyfallingList)
    {
            enemyfalling->GameObjectDelete(&mGameScene);
     }
    mEnemyfallingList.clear();

        // 3. 显示游戏结束画面
    mOverScene.setSceneRect(QRect(0,0,1024,1024));
        QGraphicsPixmapItem* gameOverItem = new QGraphicsPixmapItem(QPixmap(":/start/images/overscene.png"));
        gameOverItem->setPos(0, 0);
        mOverScene.addItem(gameOverItem);


        // 4. 添加重新开始按钮
        QToolButton* restartBtn = new QToolButton();
        restartBtn->setAutoRaise(true);
        restartBtn->resize(400, 100);
        restartBtn->setIcon(QIcon(":/start/images/restartbutton.png"));
        restartBtn->setIconSize(QSize(400, 100));
        restartBtn->move(312, 700);


        connect(restartBtn, &QToolButton::clicked, [this]() {
            // 清除游戏结束画面
            mOverScene.clear();

            // 重新加载游戏场景
            GameInit();
        });

        mOverScene.addWidget(restartBtn);

        mGameView.setScene(&mOverScene);
        mGameView.show();


}

void GameControl::playermove()
{
    for(int keyCode : mKeyList)
    {
        switch (keyCode)
        {
        case   Qt::Key_A:mmyplayer.moveBy(-1*mmyplayer.Movespeed(),0);break;
        case   Qt::Key_D:mmyplayer.moveBy(1*mmyplayer.Movespeed(),0);break;
        }
    }

    //边界判断
    if (mmyplayer.x()<0)
    {
        mmyplayer.setX(0);
    }
    if (mmyplayer.y()<914)
    {
        mmyplayer.setY(914);
    }
    if (mmyplayer.x()>840)
    {
        mmyplayer.setX(840);
    }
    if (mmyplayer.y()>914)
    {
        mmyplayer.setY(914);
    }
}


void GameControl::Createfalling()
{

    // Enemyfalling *enemyfalling =new Enemyfalling(QPoint(randX,-224),pixmap);

    //对象池获取对象
    int randType=rand()%(4);
    switch(randType)
    {
    case 0:{QPixmap pixmap(":/falling/images/bomb.png");
        int randX=rand()%(800);
        GameObject*obj=GameObjectPool::Instance()->GetGameObject(GameObject::QT_Enemyfalling);
        Enemyfalling*enemyfalling=(Enemyfalling*)obj;
        enemyfalling->Init(QPoint(randX,-224),pixmap);
        enemyfalling->setData(Qt::UserRole + 1, QString("bomb.png"));



        //添加到场景
        mGameScene.addItem(enemyfalling);

        //添加到管理器
        mEnemyfallingList.append(enemyfalling);
        break;}
    case 1:{QPixmap pixmap(":/falling/images/candy.png");
        int randX=rand()%(800);
        GameObject*obj=GameObjectPool::Instance()->GetGameObject(GameObject::QT_Enemyfalling);
        Enemyfalling*enemyfalling=(Enemyfalling*)obj;
        enemyfalling->Init(QPoint(randX,-224),pixmap);
        enemyfalling->setData(Qt::UserRole + 1, QString("candy.png"));


        //添加到场景
        mGameScene.addItem(enemyfalling);

        //添加到管理器
        mEnemyfallingList.append(enemyfalling);
        break;}
    case 2:{QPixmap pixmap(":/falling/images/chocolate_cake.png");
        int randX=rand()%(800);
        GameObject*obj=GameObjectPool::Instance()->GetGameObject(GameObject::QT_Enemyfalling);
        Enemyfalling*enemyfalling=(Enemyfalling*)obj;
        enemyfalling->Init(QPoint(randX,-224),pixmap);
        enemyfalling->setData(Qt::UserRole + 1, QString("chocolate_cake.png"));


        //添加到场景
        mGameScene.addItem(enemyfalling);

        //添加到管理器
        mEnemyfallingList.append(enemyfalling);
        break;}
    case 3:{QPixmap pixmap(":/falling/images/strawberry_cake.png");
        int randX=rand()%(800);
        GameObject*obj=GameObjectPool::Instance()->GetGameObject(GameObject::QT_Enemyfalling);
        Enemyfalling*enemyfalling=(Enemyfalling*)obj;
        enemyfalling->Init(QPoint(randX,-224),pixmap);
        enemyfalling->setData(Qt::UserRole + 1, QString("strawberry_cake.png"));


        //添加到场景
        mGameScene.addItem(enemyfalling);

        //添加到管理器
        mEnemyfallingList.append(enemyfalling);
        break;}
    }
    // QPixmap pixmap(":/falling/images/bomb.png");
    // int randX=rand()%(800);
    // GameObject*obj=GameObjectPool::Instance()->GetGameObject(GameObject::QT_Enemyfalling);
    // Enemyfalling*enemyfalling=(Enemyfalling*)obj;
    // enemyfalling->Init(QPoint(randX,-224),pixmap);


    // //添加到场景
    // mGameScene.addItem(enemyfalling);

    // //添加到管理器
    // mEnemyfallingList.append(enemyfalling);
}
